//
//  XJhistoryListVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/12/28.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "XJhistoryListVC.h"

@interface XJhistoryListVC ()
{
    NSMutableArray *_dataSourece;
    NSInteger lastID;
    NSInteger userID;
    UIButton *_starTimeTF;
    UIButton *_stopTimeTF;
    NSInteger tag;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
}
@property (nonatomic,strong)UITableView *tableview;
@property (nonatomic,strong)AFHTTPSessionManager *manager;

@end

@implementation XJhistoryListVC
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0xf0f0f0);
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *dele = app.delegate;
    userID = dele.userId;
    _dataSourece = [[NSMutableArray alloc]init];
    //NSSLog(@"%ld",self.stationId);
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableview.rowHeight = 55.0f;
    _tableview.dataSource = self;
    _tableview.delegate = self;
    _tableview.backgroundColor = [UIColor clearColor];
    UIView *heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 44)];
    heardView.backgroundColor = [UIColor whiteColor];
    UILabel *timeLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 25, 21)];
    timeLab.text = @"📅";
    timeLab.font = [UIFont systemFontOfSize:15.0];
    timeLab.textColor = UIColorFromRGB(0x4d4d4d);
    [heardView addSubview:timeLab];

    _starTimeTF = [UIButton buttonWithType:UIButtonTypeSystem];
    _starTimeTF.frame = CGRectMake(40, 8, (kSCREEN_WIDTH-98)/2, 25);
    [_starTimeTF setTitle:@"选择开始时间" forState:UIControlStateNormal];
    [_starTimeTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
    _starTimeTF.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _starTimeTF.titleLabel.font = [UIFont systemFontOfSize:15.0];
    _starTimeTF.layer.cornerRadius = 5;
    //btn标题对齐方式
    _starTimeTF.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_starTimeTF addTarget:self action:@selector(chooseTime:) forControlEvents:UIControlEventTouchUpInside];
    _starTimeTF.tag = 1001;
    [heardView addSubview:_starTimeTF];

    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_starTimeTF.frame), CGRectGetMinY(_starTimeTF.frame), 8, 21)];
    line.text = @"-";
    line.textColor = UIColorFromRGB(0xb6b6b6);
    [heardView addSubview:line];

    
    _stopTimeTF = [UIButton buttonWithType:UIButtonTypeSystem];
    _stopTimeTF.frame = CGRectMake(CGRectGetMaxX(line.frame), 8, (kSCREEN_WIDTH-98)/2, 25);
    [_stopTimeTF setTitle:@"选择结束时间" forState:UIControlStateNormal];
    [_stopTimeTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
    _stopTimeTF.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _stopTimeTF.titleLabel.font = [UIFont systemFontOfSize:15.0];
    _stopTimeTF.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    _stopTimeTF.layer.cornerRadius = 5;
    [_stopTimeTF addTarget:self action:@selector(chooseTime:) forControlEvents:UIControlEventTouchUpInside];
    _stopTimeTF.tag = 1002;
    [heardView addSubview:_stopTimeTF];
    UIButton *SearchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    SearchBtn.frame = CGRectMake(CGRectGetMaxX(_stopTimeTF.frame)+10, 8, 25, 25);
    [SearchBtn setImage:[[UIImage imageNamed:@"seach_icon_b"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [SearchBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    [heardView addSubview:SearchBtn];
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(0, 43, kSCREEN_WIDTH, 1)];
    line1.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [heardView addSubview:line1];
    
    _tableview.tableHeaderView = heardView;
    _tableview.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableview];
    [self netWorking];
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        lastID = -1;
        [_dataSourece removeAllObjects];
        [_starTimeTF setTitle:@"选择开始时间" forState:UIControlStateNormal];
        [_starTimeTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
        [_stopTimeTF setTitle:@"选择结束时间" forState:UIControlStateNormal];
        [_stopTimeTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];

        [self netWorking];
    }];
    
    _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        YYXJhisListModel *model = [_dataSourece lastObject];
        lastID = model.inspectId;
        [self netWorking];
    }];

}
/**
 *  停止刷新
 */
-(void)endRefresh{
    
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
}

- (void)netWorking{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:XJhisListURL parameters:@{@"userId":[NSString stringWithFormat:@"%ld",self.userID],@"stationId":[NSString stringWithFormat:@"%ld",self.stationId],@"lastId":[NSString stringWithFormat:@"%ld",lastID]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        YYXJdataModel *model = [[YYXJdataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (YYXJhisListModel *ListModel in model.beanList) {
            [_dataSourece addObject:ListModel];
        }

        if (_dataSourece.count == 0 ) {
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) title:@"没有历史巡检信息"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];

        }else{
            [self.tableview reloadData];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500) {
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0,64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }


    }];
}
- (void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
- (void)NothingRefresh:(UIButton *)sender{
    [_nothing removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
- (void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
- (void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourece.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YYXJhistoryListCell *cell = [[YYXJhistoryListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    YYXJhisListModel *model = _dataSourece[indexPath.row];
    [cell fillCellWithModel:model];
    return cell;
}
/*
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    YYXJhisListModel *model = _dataSourece[indexPath.row];
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除当前历史纪录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了取消");
        }];
        
        UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (userID == model.inspectUserId) {
                //删除数据库inspectId
                //NSLog(@"%ld",model.gzID);
                [self delePlain:model.inspectId];
                //删除本地
                [_dataSourece removeObjectAtIndex:indexPath.row];
                [self.tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            else{
                
                [self showAlert:@"温馨提示" message:@"对不起，您没有权限删除当前纪录" actionWithTitle:@"确定"];
            }

        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:OKAction];
        [self presentViewController:alertVC animated:YES completion:nil];

    }];
    return @[deleteRowAction];
}
 
*/
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
    
}



- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath



{

    return UITableViewCellEditingStyleDelete;
    
}



-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (editingStyle ==UITableViewCellEditingStyleDelete) {
        
        
        
//        [self.dataSourceremoveObjectAtIndex:indexPath.row];
//        
//        [self.tableViewdeleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }
    
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    
     YYXJhisListModel *model = _dataSourece[indexPath.row];
    
    //设置删除按钮
    
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除当前历史纪录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了取消");
        }];
        
        UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (userID == model.inspectUserId) {
                //删除数据库inspectId
                //NSLog(@"%ld",model.gzID);
                [self delePlain:model.inspectId];
                //删除本地
                [_dataSourece removeObjectAtIndex:indexPath.row];
                [self.tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            else{
                
                [self showAlert:@"温馨提示" message:@"对不起，您没有权限删除当前纪录" actionWithTitle:@"确定"];
            }
            
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:OKAction];
        [self presentViewController:alertVC animated:YES completion:nil];

        
    }];
    
    
    /*
    //设置收藏按钮
    
    UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"收藏"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
        
        collectRowAction.backgroundColor = [UIColor greenColor];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"收藏"message:@"收藏成功"delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil,nil];
        
        [alertView show];
        
    }];
    collectRowAction.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    collectRowAction.backgroundColor = [UIColor grayColor];*/
    return  @[deleteRowAction];
    
}

/*
 列表删除指令
 */
- (void)delePlain:(NSInteger)inspectId{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"删除中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:XJhisListDeletURL parameters:@{@"inspectId":[NSString stringWithFormat:@"%ld",inspectId]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //NSSLog(@"%@",dic);
        if ([dic[@"status"]integerValue]==1) {
            [self showAlert:@"温馨提示" message:dic[@"message"] actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"温馨提示" message:dic[@"message"] actionWithTitle:@"我知道了"];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500) {
            [self showAlert:@"温馨提示" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YYXJhisListModel *model = _dataSourece[indexPath.row];
    XJRecordVC *vc = [[XJRecordVC alloc]init];
    vc.DetailArray = [[NSMutableArray alloc]init];
    [vc.DetailArray addObject:model];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)chooseTime:(UIButton *)sender{
    
    tag = sender.tag;
    
    CJCalendarViewController *calendarController = [[CJCalendarViewController alloc] init];
    calendarController.view.frame = self.view.frame;
    
    calendarController.delegate = self;
    NSArray *arr = [sender.titleLabel.text componentsSeparatedByString:@"-"];
    
    if (arr.count > 1) {
        [calendarController setYear:arr[0] month:arr[1] day:arr[2]];
    }
    
    [self presentViewController:calendarController animated:YES completion:nil];
    
}

-(void)CalendarViewController:(CJCalendarViewController *)controller didSelectActionYear:(NSString *)year month:(NSString *)month day:(NSString *)day{
    
    if (tag == 1001) {
        
        if (day.length == 1 && month.length != 1) {
            
            [_starTimeTF setTitle:[NSString stringWithFormat:@"%@-%@-0%@", year, month,day] forState:UIControlStateNormal];
        }else if (month.length == 1 && day.length != 1){
            
            [_starTimeTF setTitle:[NSString stringWithFormat:@"%@-0%@-%@", year, month, day] forState:UIControlStateNormal];
        }else if (month.length == 1 && day.length ==1 ){
            [_starTimeTF setTitle:[NSString stringWithFormat:@"%@-0%@-0%@", year, month, day] forState:UIControlStateNormal];
        } else{
            
            [_starTimeTF setTitle:[NSString stringWithFormat:@"%@-%@-%@", year, month, day] forState:UIControlStateNormal];
        }
        [_starTimeTF setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        
    }else{
        
        if (day.length == 1 && month.length != 1) {
            
            [_stopTimeTF setTitle:[NSString stringWithFormat:@"%@-%@-0%@", year, month,day] forState:UIControlStateNormal];
        }else if (month.length == 1 && day.length != 1){
            
            [_stopTimeTF setTitle:[NSString stringWithFormat:@"%@-0%@-%@", year, month, day] forState:UIControlStateNormal];
        }else if (month.length == 1 && day.length ==1 ){
            [_stopTimeTF setTitle:[NSString stringWithFormat:@"%@-0%@-0%@", year, month, day] forState:UIControlStateNormal];
        } else{
            
            [_stopTimeTF setTitle:[NSString stringWithFormat:@"%@-%@-%@", year, month, day] forState:UIControlStateNormal];
        }
        [_stopTimeTF setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
    }
    
    
}
- (void)searchClick{
    
    [_dataSourece removeAllObjects];
//    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        lastID = -1;
//        [_dataSourece removeAllObjects];
//        [self netWorking];
//    }];
//    
//    _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        YYXJhisListModel *model = [_dataSourece lastObject];
//        lastID = model.inspectId;
//        [self searchNetWorking];
//    }];

    [self searchNetWorking];
}
- (void)searchNetWorking{
    
    if ([_starTimeTF.titleLabel.text isEqualToString:@"选择开始时间"] || [_stopTimeTF.titleLabel.text isEqualToString:@"选择结束时间"]) {
        [self showAlert:@"温馨提示" message:@"请选择时间" actionWithTitle:@"确定"];
    }else{
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:XJsearchURL parameters:@{@"stationId":[NSString stringWithFormat:@"%ld",self.stationId],@"startTime":_starTimeTF.titleLabel.text,@"endTime":_stopTimeTF.titleLabel.text,@"lastId":[NSString stringWithFormat:@"%ld",lastID]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        YYXJdataModel *model = [[YYXJdataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (YYXJhisListModel *ListModel in model.beanList) {
            [_dataSourece addObject:ListModel];
        }
        if (_dataSourece.count == 0) {
            
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) title:@"没有搜索到您要的信息,点击刷新返回原始数据"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }
            self.tableview.alpha = 1;
            [self.tableview reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
